package eerbaar.v2.app.tasks;

import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;

import eerbaar.v2.app.tasks.IGameTask.Priority;

public class AppLoop {

    private final List<IGameTask> list = new ArrayList<IGameTask>();
    private int count;
    private boolean suspended;

    public AppLoop() {
        //
    }

    public void add(IGameTask task) {

        if (!this.list.contains(task)) {
            this.list.add(task);
        }
    }

    public void clear() {

        this.list.clear();
    }

    public void doLoop(Graphics2D g) {

        loopPriority(g, Priority.FIRST);
        loopPriority(g, Priority.MIDDLE);
        loopPriority(g, Priority.LAST);
        loopPriority(g, Priority.AFTER_LAST);
        loopPriority(g, Priority.AFTER_AFTER_LAST);
        this.count++;
    }

    private void loopPriority(Graphics2D g, IGameTask.Priority priority) {

        for (IGameTask task : this.list) {
            if (task.getPriority() == priority) {
                loopRate(g, task);
            }
        }
    }

    private void loopRate(Graphics2D g, IGameTask task) {

        int rate = task.getRate();

        if ((this.count % rate) == 0) {

            if (this.suspended) {

                if (task.runWhenSuspended()) {
                    task.doTask(g);
                }
            } else {
                task.doTask(g);
            }
        }
    }

    public void setSuspended(boolean suspended) {
        this.suspended = suspended;
    }

}
